/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.scan;

import java.nio.file.Path;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 27/5/2017
 */
public class ResourcePatternFilter implements ScanFilter {

    public static final String SYS_KEY_SCAN_PATTERN = "cn.hermit.scan.pattern";

    private static final String DEFAULT_SCAN_PATTERNS = "cn/hermit/.*";

    private final String[] pattern;

    private final boolean excluding;

    public ResourcePatternFilter() {
        this(false, System.getProperty(SYS_KEY_SCAN_PATTERN, DEFAULT_SCAN_PATTERNS).split(","));
    }

    public ResourcePatternFilter(String... pattern) {
        this(false, pattern);
    }

    public ResourcePatternFilter(boolean excluding, String... pattern) {
        this.excluding = excluding;
        this.pattern = pattern;
    }

    @Override
    public boolean filter(ClassLoader classLoader, String resourceName, Path path) throws Throwable {
        if (pattern == null || pattern.length == 0) {
            return true;
        }
        for (String p : pattern) {
            if (resourceName.matches(p)) {
                if (excluding) {
                    return false;
                }
            } else {
                if (!excluding) {
                    return false;
                }
            }
        }
        return true;
    }
}
